package org.third.integration.kubernates.cmd.imp.client.imp;

import java.io.IOException;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.third.common.utils.EnvUtils;
import org.third.common.utils.HttpClientUtils;
import org.third.common.utils.StreamUtils;
import org.third.integration.kubernates.cmd.imp.client.KubeRquestClient;
import org.third.integration.kubernates.cmd.imp.client.bean.ApiServerResponse;

@Component
public class KubeRquestClientImp implements KubeRquestClient{
	
	private CloseableHttpClient httpClient = HttpClientUtils.getCertificateIngnoredHttpClient();
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	private String authToken;
	
	public KubeRquestClientImp() throws IOException{
		this.authToken = StreamUtils.getFileContent(EnvUtils.getApiservertokenfile());
	}
	
	@Override
	public ApiServerResponse requestK8s(HttpUriRequest request) {
		request.setHeader("Authorization", "Bearer " + this.authToken);
		ApiServerResponse apiServerResponse = new ApiServerResponse();
		CloseableHttpResponse response= null;
		try {
			response = httpClient.execute(request);
			int statusCode = response.getStatusLine().getStatusCode();
			String responseBody = StreamUtils.streamToString(response.getEntity().getContent());
			apiServerResponse.setStatusCode(statusCode);
			apiServerResponse.setResponseBody(responseBody);
		} catch (Exception e) {
			apiServerResponse.setException(e);
			logger.warn("something wrong when call the api server", e);
		}finally{
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					logger.warn(e.getMessage());
				}
			 }
		}
		return apiServerResponse;
	}
	
}
